<?php
/**
 * Created by PhpStorm.
 * User: 86151 - 姜伟
 * Date: 2021/6/10
 * Time: 20:46.
 */

namespace Xinyu\Gen\Commands;

use Xinyu\Gen\Core\GenClient;
use Illuminate\Console\Command;

class MakeRouteCommand extends Command
{
    /**
     * --name 【模型名】
     * --desc 【模块描述】.
     */
    protected $signature = 'makeRoute {--name=} {--desc=}';

    protected $description = '生成路由脚本';

    public function handle()
    {
        if ('local' !== env('APP_ENV')) {
            $this->error('该环境不允许执行该脚本');
            return false;
        }
        $this->makeRoute();
    }

    // 生成路由脚本
    public function makeRoute()
    {
        $res = GenClient::getInstance()->makeRoute([
            'name' => $this->option('name'),
            'desc' => $this->option('desc'),
        ]);
        if (-1 === $res['code']) {
            $this->error($res['msg']);
        } else { // 存进`/zapidoc/route/route.php`
            $dirPath = base_path() . '/zapidoc/route';
            if (!is_dir($dirPath)) {
                if (!mkdir($dirPath, 0755, true) && !is_dir($dirPath)) {
                    throw new \RuntimeException(sprintf('目录"%s"没有被创建', $dirPath));
                }
            }
            $savePath = $dirPath . '/route.php';
            file_put_contents($savePath, '<?php' . str_repeat(PHP_EOL, 2) . $res['msg']);
            $this->info("请到路径`{$savePath}`中查看信息");
        }
    }
}
